#import "Controller.h"

@implementation Controller

- (id) init
{
	if( self = [super init] )
	{
		// Initializes a CamelBones perl object, then grabs a shared pointer to it.
		[CBPerl stubInit:CBGetPerlArchver()];
		perl = [CBPerl sharedPerl];
		
		// This is specifically our perl object.  The class name needs to be 
		// exactly the same as your perl module's name, sans the .pm
		perlObj = [[NSClassFromString(@"SimpleRegex") alloc] init];
	}
	
	return( self );
}

- (IBAction)clear:(id)sender
{
	[textField setStringValue:@""];
	[regexField setStringValue:@""];
	[resultsField setStringValue:@""];
}

- (IBAction)okError:(id)sender
{
	[errorWindow orderOut:sender];
	
	[NSApp endSheet:errorWindow returnCode:0];
}

- (IBAction)runIt:(id)sender
{
	NSString *regexTest;
	NSString *parsedText;

	if( [[textField stringValue] isEqualTo:@""] )
	{
		[errorMsg setStringValue:@"Please put something in the Text field"];
		[self showError];
		return;
	}
	
	if( [[regexField stringValue] isEqualTo:@""] )
	{
		[errorMsg setStringValue:@"Please put something in the regex field"];
		[self showError];
		return;
	}

	// Run a test against the regex to see if it's valid.  if not, setup an error message
	regexTest = [perlObj p_testRegex:[NSString stringWithFormat:@"$testString =~ %@", [regexField stringValue]]];
	if( ![regexTest isEqualTo:@""] )
	{
		// Regex failed
		[errorMsg setStringValue:[NSString stringWithFormat:@"regex failed: %@", regexTest]];
		[self showError];
	}
	else
	{
		// Execute the perl routine
		parsedText = [perlObj p_parseRegex:[NSString stringWithFormat:@"$text =~ %@", [regexField stringValue]]
									onText:[textField stringValue]];
		
		// Set the results field
		[resultsField setStringValue:parsedText];
	}
}

-(void) showError
{
	[NSApp beginSheet:errorWindow
			modalForWindow:mainWindow
			modalDelegate:self
			didEndSelector:nil //@selector(sheetDidEnd:returnCode:contextInfo:)
			contextInfo:nil];
}

@end
